<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java面试,">










<meta name="description" content="本文学习《剑指Java面试-Offer直通车》第一章和第六章，主要内容为: 课程导学和Java底层知识：JVM视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta name="keywords" content="Java面试">
<meta property="og:type" content="article">
<meta property="og:title" content="【一】剑指Java面试Offer直通车-课程简介与Java底层知识：JVM">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/12/08/java-interview-offer-1/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文学习《剑指Java面试-Offer直通车》第一章和第六章，主要内容为: 课程导学和Java底层知识：JVM视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191210163726081.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191210164102152.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191212105423422.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191210172257379.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191211150524729.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191211153614424.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191211161438825.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217060918930.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217060956651.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217063943782.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217093721063.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217065239908.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217065334720.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217103919761.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217104814936.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217105544326.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217111554487.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217111451749.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217124018555.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217140122164.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217140515022.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217142013010.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217152432416.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217172604475.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191218064330907.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191218120630804.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191218140610157.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191218150352284.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217142013010.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191218144127567.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191217092006619.jpg">
<meta property="og:updated_time" content="2019-12-18T07:28:02.880Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【一】剑指Java面试Offer直通车-课程简介与Java底层知识：JVM">
<meta name="twitter:description" content="本文学习《剑指Java面试-Offer直通车》第一章和第六章，主要内容为: 课程导学和Java底层知识：JVM视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191210163726081.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/12/08/java-interview-offer-1/">





  <title>【一】剑指Java面试Offer直通车-课程简介与Java底层知识：JVM | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/12/08/java-interview-offer-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【一】剑指Java面试Offer直通车-课程简介与Java底层知识：JVM</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-08T11:59:13+08:00">
                2019-12-08
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java基础/" itemprop="url" rel="index">
                    <span itemprop="name">Java基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文学习《剑指Java面试-Offer直通车》第一章和第六章，主要内容为: 课程导学和Java底层知识：JVM<br>视频课程地址：<a href="https://coding.imooc.com/class/303.html" target="_blank" rel="noopener">https://coding.imooc.com/class/303.html</a><br>项目代码地址：<a href="https://gitee.com/aiolos123/java_basic" target="_blank" rel="noopener">https://gitee.com/aiolos123/java_basic</a></p>
<a id="more"></a>

<h2 id="课程简介"><a href="#课程简介" class="headerlink" title="课程简介"></a>课程简介</h2><ol>
<li><p>课程内容<br><img src="/blog/images/20191210163726081.jpg" alt="课程内容"></p>
</li>
<li><p>本课程JDK版本选择：JDK8和JDK11<br><img src="/blog/images/20191210164102152.jpg" alt="本课程JDK版本选择"></p>
</li>
<li><p><strong>剥离出不变的通用知识点，重在平时积累，深入研究知识点</strong></p>
</li>
<li><p>合理利用搜索引擎，培养主动解决问题的能力。</p>
</li>
<li><p>本课程只列出高频面试点</p>
</li>
</ol>
<h2 id="谈谈你对Java的理解"><a href="#谈谈你对Java的理解" class="headerlink" title="谈谈你对Java的理解"></a>谈谈你对Java的理解</h2><p>即Java语言的特点：平台无关性(Compile Once、Run Anywhere、一次编译、多处运行)、GC(垃圾回收)、语言特性(泛型、反射、lambda表达式)、面向对象、类库、异常处理</p>
<h2 id="平台无关性如何实现"><a href="#平台无关性如何实现" class="headerlink" title="平台无关性如何实现"></a>平台无关性如何实现</h2><blockquote>
<p>答案见1.4： Java源码首先被编译成字节码，再由不同平台的JVM进行解析。Java语言在不同的平台上运行时不需要进行重新编译，JVM在执行字节码时，把字节码转换成具体平台上的机器指令</p>
</blockquote>
<p>个人理解平台无关性的原理如下图(JVM屏蔽了底层操作系统的差异，提供了统一的运行平台)：<br><img src="/blog/images/20191212105423422.jpg" alt="个人理解平台无关性的原理"></p>
<h3 id="编译时：将java源文件编译为class文件"><a href="#编译时：将java源文件编译为class文件" class="headerlink" title="编译时：将java源文件编译为class文件"></a>编译时：将java源文件编译为class文件</h3><blockquote>
<p>class文件为java源文件编译成的二进制字节码文件，其中保存了Java类的属性、方法及类中常量信息，并且会添加一个公有的静态常量属性class，记录了这个java类的相关信息，它是Class类的实例</p>
</blockquote>
<p>1.1. 编译java文件————通过javac指令<br><img src="/blog/images/20191210172257379.jpg" alt="编译java文件"></p>
<p>1.2. 通过javap -c指令(对代码进行反汇编)来查看class文件<br><img src="/blog/images/20191211150524729.jpg" alt="查看class文件"></p>
<p>1.3. class文件中的具体代码如下(其中的中文为本人添加的注释)：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">Compiled from <span class="string">"ByteCodeSample01.java"</span>       <span class="comment">//这个类编译自"ByteCodeSample01.java"</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">com</span>.<span class="title">aiolos</span>.<span class="title">interview</span>.<span class="title">java06</span>.<span class="title">ByteCodeSample01</span> &#123;</span>  <span class="comment">//定义带有包名的类</span></span><br><span class="line">  <span class="keyword">public</span> com.aiolos.interview.java06.ByteCodeSample01();   <span class="comment">//编译器生成的默认无参构造函数</span></span><br><span class="line">    Code:                                   <span class="comment">//Code中即为ByteCodeSample01()这个无参构造函数要执行的代码</span></span><br><span class="line">       <span class="number">0</span>: aload_0                           <span class="comment">//在非静态方法中，aload_0表示对this进行操作，在static 方法中，aload_0表示对方法的第一参数的操作。</span></span><br><span class="line">       <span class="number">1</span>: invokespecial #<span class="number">1</span>                  <span class="comment">// Method java/lang/Object."&lt;init&gt;":()V————即调用父类的构造方法super()进行初始化</span></span><br><span class="line">       <span class="number">4</span>: <span class="keyword">return</span>                            <span class="comment">// 退出这个构造函数</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> main(java.lang.String[]);  <span class="comment">//Java内存中的堆和栈，局部变量在栈中操作</span></span><br><span class="line">    Code:                                   <span class="comment">//Code表示这个函数要执行的代码</span></span><br><span class="line">       <span class="number">0</span>: bipush        <span class="number">6</span>                   <span class="comment">//当int取值-128~127时，JVM采用bipush指令将常量6压入栈中。</span></span><br><span class="line">       <span class="number">2</span>: istore_1                          <span class="comment">//将这个数值6从栈存储到局部变量1中，即i中</span></span><br><span class="line">       <span class="number">3</span>: bipush        <span class="number">7</span></span><br><span class="line">       <span class="number">5</span>: istore_2</span><br><span class="line">       <span class="number">6</span>: iinc          <span class="number">1</span>, <span class="number">1</span>                <span class="comment">//调用iinc函数，将局部变量1加1，即i加1</span></span><br><span class="line">       <span class="number">9</span>: iinc          <span class="number">2</span>, <span class="number">1</span>                <span class="comment">//调用iinc函数，将局部变量2加1，即j加1</span></span><br><span class="line">      <span class="number">12</span>: getstatic     #<span class="number">2</span>                  <span class="comment">// Field java/lang/System.out:Ljava/io/PrintStream;  //获取类的静态属性——PrintStream，准备打印，并压入栈中</span></span><br><span class="line">      <span class="number">15</span>: iload_1                           <span class="comment">//将局部变量1即i的值加载到栈中,准备打印</span></span><br><span class="line">      <span class="number">16</span>: invokevirtual #<span class="number">3</span>                  <span class="comment">// Method java/io/PrintStream.println:(I)V  //调用println方法打印i的值</span></span><br><span class="line">      <span class="number">19</span>: getstatic     #<span class="number">2</span>                  <span class="comment">// Field java/lang/System.out:Ljava/io/PrintStream;</span></span><br><span class="line">      <span class="number">22</span>: iload_2</span><br><span class="line">      <span class="number">23</span>: invokevirtual #<span class="number">3</span>                  <span class="comment">// Method java/io/PrintStream.println:(I)V</span></span><br><span class="line">      <span class="number">26</span>: <span class="keyword">return</span>                            <span class="comment">// 退出方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>1.4. 这些指令就是JVM所能理解的字节码(即class文件)</p>
<blockquote>
<p>Java提供了不同平台上的JVM，而class文件就是跨平台的基础</p>
</blockquote>
<p><img src="/blog/images/20191211153614424.jpg" alt="JVM所能理解的字节码"></p>
<p>1.5. 为什么JVM不直接将源码解析成机器码去执行</p>
<blockquote>
<p>a. 如果直接解析成机器码，则每次执行都需要进行语法、句法检查、语义分析(因为这些检查分析不会保存到机器码中)<br>b. 也可以将别的语言如Scala、Ruby等解析为字节码，而不一定必须是Java语言，增加了平台的兼容性、扩展性</p>
</blockquote>
<h3 id="运行时：JVM运行class文件"><a href="#运行时：JVM运行class文件" class="headerlink" title="运行时：JVM运行class文件"></a>运行时：JVM运行class文件</h3><h2 id="JVM如何加载和运行class文件"><a href="#JVM如何加载和运行class文件" class="headerlink" title="JVM如何加载和运行class文件"></a>JVM如何加载和运行class文件</h2><blockquote>
<p>答案： 由ClassLoader加载符合特定格式的class文件到内存；由Execution Engine对加载到内存中的class文件进行解析并提交到操作系统中运行程序；</p>
</blockquote>
<ol>
<li><p>JVM(Java虚拟机)： 是抽象化的计算机，通过在实际的计算机上仿真、虚拟出完善的计算机功能。</p>
</li>
<li><p>JVM有自己完善的硬件架构，如处理器、堆栈、、指令系统等。</p>
</li>
<li><p>JVM屏蔽了与具体操作系统平台相关的信息、使得Java程序只需生成可在JVM上运行的class文件，就可以不加修改的在多种平台的JVM上运行。</p>
</li>
<li><p>JVM屏蔽底层操作系统的不同，减少基于底层语言开发的复杂性。</p>
</li>
<li><p><strong>JVM是一个内存中的虚拟机，即JVM的存储就是内存，我们编写的变量、方法都保存在内存中</strong></p>
</li>
<li><p>JVM的架构如下：<br><img src="/blog/images/20191211161438825.jpg" alt="JVM的架构"></p>
</li>
<li><p>JVM中的两个重点：JVM内存结构模型、GC</p>
</li>
</ol>
<h2 id="什么是反射"><a href="#什么是反射" class="headerlink" title="什么是反射"></a>什么是反射</h2><blockquote>
<p>反射： 动态将Java类中各种成分映射成对象，并可以调用的一种机制</p>
</blockquote>
<ol>
<li><p>Java反射机制是在运行状态中，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意方法和属性；这种<strong>动态获取信息以及动态调用对象方法的功能</strong>就称为Java语言的反射机制。</p>
</li>
<li><p>写一个反射的例子</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> class ReflectSample &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> main(<span class="keyword">String</span>[] args) <span class="keyword">throws</span> ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException &#123;</span><br><span class="line">        Class rc = Class.forName(<span class="string">"com.aiolos.interview.java06.reflect.Robot"</span>);</span><br><span class="line">        Robot r = (Robot) rc.newInstance();</span><br><span class="line">        System.out.<span class="built_in">println</span>(<span class="string">"Class name is "</span> + rc.getName()); <span class="comment">//Class name is com.aiolos.interview.java06.reflect.Robot</span></span><br><span class="line">        Method getHello = rc.getDeclaredMethod(<span class="string">"throwHello"</span>, <span class="keyword">String</span>.class);</span><br><span class="line">        getHello.setAccessible(<span class="keyword">true</span>); <span class="comment">//设置可以访问</span></span><br><span class="line">        <span class="keyword">Object</span> <span class="built_in">str</span> = getHello.invoke(r, <span class="string">"Bob"</span>);</span><br><span class="line">        System.out.<span class="built_in">println</span>(<span class="string">"getHello result is "</span> + <span class="built_in">str</span>); <span class="comment">//getHello result is Hello Bob</span></span><br><span class="line"></span><br><span class="line">        Method sayHi = rc.getMethod(<span class="string">"sayHi"</span>, <span class="keyword">String</span>.class);</span><br><span class="line">        sayHi.invoke(r, <span class="string">"Welcome"</span>); <span class="comment">//Welcome null</span></span><br><span class="line"></span><br><span class="line">        Field name = rc.getDeclaredField(<span class="string">"name"</span>);</span><br><span class="line">        name.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">        name.<span class="built_in">set</span>(r, <span class="string">"Alice"</span>);</span><br><span class="line">        sayHi.invoke(r, <span class="string">"Welcome"</span>);  <span class="comment">//Welcome Alice</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>总结反射： 要获取类的属性、方法 &lt;– 先获取类的Class对象 &lt;– 先获取该类的字节码文件</p>
<h2 id="谈谈ClassLoader"><a href="#谈谈ClassLoader" class="headerlink" title="谈谈ClassLoader"></a>谈谈ClassLoader</h2><ol>
<li><p>类从编译到执行的过程</p>
<blockquote>
<p>a. 编译器将Robot.java源文件编译为Robot.class字节码文件<br>b. ClassLoader将字节码转换为JVM中的Class<robot>对象(获取到的字节码是以Byte数组进行传递的)<br>c. JVM利用Class<robot>对象实例化为Robot对象</robot></robot></p>
</blockquote>
</li>
<li><p>ClassLoader的作用</p>
<blockquote>
<p>ClassLoader在Java中有着非常重要的作用，它主要工作在CLass装载的加载阶段，<br>其主要作用是从系统外部获得Class二进制数据流，它是Java的核心组件。<br>所有的Class都是由ClassLoader进行加载的，ClassLoader负责通过将Class文件的二进制数据流装载进系统<br>然后交给Java虚拟机进行连接、初始化等操作。</p>
</blockquote>
</li>
<li><p>ClassLoader源码分析</p>
<blockquote>
<p>定义了类的加载流程和加载方式。核心是loadClass()方法</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191217060918930.jpg" alt="ClassLoader源码分析"></p>
<ol start="4">
<li><p>ClassLoader的四大种类</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a. BootStrapClassLoader：C++编写，用于加载java自带的核心类java.*, 如java.lang。通常这些核心类被签名的，不能被替换，由JNI内核实现，是其他ClassLoader的基础。</span><br><span class="line">b. ExtClassLoader：Java编写，加载扩展库javax.*。是用户可见的ClassLoader(即可以看到其<span class="class"><span class="keyword">class</span>文件)。</span></span><br><span class="line">用到才加载如下路径System.<span class="keyword">out</span>.println(System.getProperty(<span class="string">"java.ext.dirs"</span>))中的<span class="class"><span class="keyword">class</span>文件</span></span><br><span class="line">c. AppClassLoader：Java编写，加载System.getProperty(<span class="string">"java.class.path"</span>)路径下的<span class="class"><span class="keyword">class</span>文件</span>(包括程序所在目录)。是用户可见的ClassLoader(即可以看到其<span class="class"><span class="keyword">class</span>文件)。</span></span><br><span class="line">d. 用户自定义ClassLoader：Java编写，定制化加载</span><br></pre></td></tr></table></figure>
</li>
<li><p>自定义ClassLoader的实现<br>自定义ClassLoader的实现的关键函数：<br><img src="/blog/images/20191217060956651.jpg" alt="自定义ClassLoader的实现"></p>
</li>
</ol>
<p>自定义ClassLoader的实现的代码如下：</p>
<figure class="highlight haxe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.aiolos.interview.java06.loader;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自定义ClassLoader</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyClassLoader</span> <span class="keyword"><span class="keyword">extends</span> <span class="type">ClassLoader</span></span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">String</span> path; <span class="comment">//待加载类的class文件的路径</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">String</span> classLoaderName;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> MyClassLoader(<span class="keyword">String</span> path, <span class="keyword">String</span> classLoaderName) &#123;</span><br><span class="line">        <span class="built_in">this</span>.path = path;</span><br><span class="line">        <span class="built_in">this</span>.classLoaderName = classLoaderName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用于寻找类文件，</span></span><br><span class="line"><span class="comment">     * 将类的class文件以byte数组的形式加载进来，并传递给defineClass</span></span><br><span class="line"><span class="comment">     * @param name 类的全路径</span></span><br><span class="line"><span class="comment">     * @return 类的class文件的字节流</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    @Override</span><br><span class="line">    <span class="keyword">public</span> Class findClass(<span class="keyword">String</span> name)&#123;</span><br><span class="line">        byte[] b = loadClassData(name); <span class="comment">//可以操作二进制流</span></span><br><span class="line">        <span class="keyword">return</span> defineClass(name, b, <span class="number">0</span>, b.length);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用于加载类的class文件</span></span><br><span class="line"><span class="comment">     * @param name </span></span><br><span class="line"><span class="comment">     * @return</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> byte[] loadClassData(<span class="keyword">String</span> name) &#123;</span><br><span class="line">        name = path + name + <span class="string">".class"</span>;</span><br><span class="line">        InputStream <span class="keyword">in</span> = <span class="literal">null</span>; <span class="comment">//读取文件</span></span><br><span class="line">        ByteArrayOutputStream out = <span class="literal">null</span>; <span class="comment">//接收文件</span></span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            <span class="keyword">in</span> = <span class="keyword">new</span> <span class="type">FileInputStream</span>(<span class="keyword">new</span> <span class="type">File</span>(name));</span><br><span class="line">            out = <span class="keyword">new</span> <span class="type">ByteArrayOutputStream</span>();</span><br><span class="line">            int i=<span class="number">0</span>;</span><br><span class="line">            <span class="keyword">while</span> ((i = <span class="keyword">in</span>.read()) != <span class="number">-1</span>)&#123;</span><br><span class="line">                out.write(i);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                out.close();</span><br><span class="line">                <span class="keyword">in</span>.close();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> out.toByteArray();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="ClassLoader的双亲委派机制"><a href="#ClassLoader的双亲委派机制" class="headerlink" title="ClassLoader的双亲委派机制"></a>ClassLoader的双亲委派机制</h2><blockquote>
<p>不同种类的ClassLoader加载的类的路径和方式是不同的，这是为了实现分工，各自负责自己的区块，使得逻辑明确。</p>
</blockquote>
<ol>
<li><p>双亲委派机制： 如果一个类加载器需要加载类，那么首先它会把这个类请求委派给父类加载器去完成，每一层都是如此。一直递归到顶层，当父加载器无法完成这个请求时，子类才会尝试去加载。这里的双亲其实就指的是父类，没有mother。父类也不是我们平日所说的那种继承关系，只是调用逻辑是这样。<br>引用自：<a href="https://baijiahao.baidu.com/s?id=1633056679004596814&amp;wfr=spider&amp;for=pc" target="_blank" rel="noopener">https://baijiahao.baidu.com/s?id=1633056679004596814&amp;wfr=spider&amp;for=pc</a></p>
</li>
<li><p>双亲委派机制加载类的流程图如下(从下到上查找是否已加载类，再从上向下进行委派加载)：<br><img src="/blog/images/20191217063943782.jpg" alt="双亲委派机制加载类的流程图"></p>
</li>
<li><p>分析ClassLoader中的loadClass()方法的源码，确认双亲委派机制加载类的流程<br><img src="/blog/images/20191217093721063.jpg" alt="双亲委派机制加载类的流程"><br><img src="/blog/images/20191217065239908.jpg" alt="双亲委派机制加载类的流程"></p>
</li>
<li><p>查找native findBootstrapClass()方法的源码的地址：<br><img src="/blog/images/20191217065334720.jpg" alt="查找源码"></p>
</li>
<li><p>为什么要使用双亲委派机制去加载类</p>
<blockquote>
<p>避免多份同样字节码的加载,浪费内存资源<br>用来作为类的层次划分。</p>
</blockquote>
</li>
</ol>
<h2 id="loadClass和forName的区别"><a href="#loadClass和forName的区别" class="headerlink" title="loadClass和forName的区别"></a>loadClass和forName的区别</h2><ol>
<li><p>类的两种加载方式</p>
<blockquote>
<p>a. 隐式加载: 通过new创建对象时，将隐式调用类加载器加载对应的类到JVM中<br>b. 显式加载：通过ClassLoader.loadClass或Class.forName显式加载需要的类。显式加载需要调用newInstance()来生成实例</p>
</blockquote>
</li>
<li><p>Java中类的装载过程(即类的对象的生成过程)<br><img src="/blog/images/20191217103919761.jpg" alt="Java中类的装载过程"></p>
</li>
<li><p>同为显式加载，loadClass和forName的区别</p>
<blockquote>
<p>相同点：在运行时，loadClass和forName都能获取任意和调用一个类的所有属性和方法(通过反射)<br>不同点：Class.forName得到的class是已经完成初始化了(即完成了第三步)。ClassLoader.loadClass得到的class是还没有链接的(即只完成了第一步)。</p>
</blockquote>
</li>
</ol>
<p>ClassLoader.loadClass()方法装载类的过程如下图：<br><img src="/blog/images/20191217104814936.jpg" alt="loadClass()方法装载类的过程"></p>
<p>Class.forName方法装载类的过程如下图：<br><img src="/blog/images/20191217105544326.jpg" alt="forName()方法装载类的过程"></p>
<ol start="4">
<li><p>代码验证</p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 两种方式加载Robot类，展示loadClass和forName的区别</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> ShowLoadClassAndForNameDifference &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> main(String[] args) <span class="keyword">throws</span> ClassNotFoundException &#123;</span><br><span class="line">        <span class="comment">//通过loadClass方式加载Robot,不执行Robot的静态代码块</span></span><br><span class="line">        ClassLoader classLoader = Robot.<span class="keyword">class</span>.getClassLoader();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//通过forName方式加载Robot,执行Robot的静态代码块</span></span><br><span class="line">        <span class="keyword">Class</span> c = <span class="keyword">Class</span>.forName(<span class="string">"Robot"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> Robot &#123;</span><br><span class="line">    <span class="comment">//static静态代码块是在类的初始化时执行</span></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        System.out.<span class="keyword">println</span>(<span class="string">"Hello Robot!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>loadClass和forName的区别的应用</p>
<blockquote>
<p>a. 加载数据库驱动需要使用Class.forName，因为数据库驱动类中是通过静态代码块来生成Driver对象，从而创建数据库驱动<br>b. 加载Spring IOC资源加载器获取要读入的资源、及读入Bean的配置文件需要使用loadClass，因为是为了实现SpringIOC的懒加载，从而加快Spring的初始化速度，在真正要使用类时再链接、初始化它</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191217111554487.jpg" alt="加载数据库驱动需要使用Class.forName"></p>
<p>java工程添加jar包：<br><img src="/blog/images/20191217111451749.jpg" alt="java工程添加jar包"></p>
<h2 id="JVM内存模型"><a href="#JVM内存模型" class="headerlink" title="JVM内存模型"></a>JVM内存模型</h2><ol>
<li>内存简介<blockquote>
<p>计算机所有程序都是在内存中运行的，这里说的内存包括虚拟内存</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191217124018555.jpg" alt="内存简介"></p>
<blockquote>
<p>a. 在程序执行过程中，需要不断的将内存的逻辑地址和物理地址进行映射，找到相关的指令和数据去执行<br>b. 作为操作系统进程，Java程序运行时也受限于操作系统的内存大小，即操作系统提供的可寻址的地址空间(由处理器的位数决定，常见的处理器有32位和64位)</p>
</blockquote>
<ol start="2">
<li>地址空间的划分<blockquote>
<p>地址空间划分为内核空间和用户空间<br>内核空间: 是操作系统程序和C语言的运行时的空间，包括连接计算机硬件、调度程序、及提供联网、虚拟内存等服务的逻辑和基于C的进程<br>用户空间: 除去内核空间之外的内存空间就是用户空间。也是Java进程实际运行时使用的内存空间。</p>
</blockquote>
</li>
</ol>
<ol start="3">
<li>32位处理器的系统中，进程可以访问的最大内存空间是3G，内核代码可以访问所有物理内存<br>64位处理器的系统中，进程可以访问的最大内存空间是512G，内核代码可以访问所有物理内存</li>
</ol>
<p>以32位处理器的系统为例，其内存地址空间如下：<br><img src="/blog/images/20191217140122164.jpg" alt="内存简介"></p>
<ol start="4">
<li><p>JVM内存模型在JVM中的位置<br><img src="/blog/images/20191217140515022.jpg" alt="JVM内存模型在JVM中的位置"></p>
</li>
<li><p>JVM内存模型(以JDK8为例，JDK8+的JVM内存模型都是类似的)</p>
<blockquote>
<p>Java程序运行在JVM中，运行时需要内存空间。JVM在执行Java程序时，会把它管理的内存空间划分为不同的区域，方便管理</p>
</blockquote>
</li>
</ol>
<h2 id="从线程的角度看JVM内存模型"><a href="#从线程的角度看JVM内存模型" class="headerlink" title="从线程的角度看JVM内存模型"></a>从线程的角度看JVM内存模型</h2><blockquote>
<p>即哪些内存区域是线程私有(线程独占)的，哪些内存区域是线程共享的</p>
</blockquote>
<p><img src="/blog/images/20191217142013010.jpg" alt="从线程的角度看JVM内存模型"></p>
<h3 id="JVM内存模型之线程独占部分"><a href="#JVM内存模型之线程独占部分" class="headerlink" title="JVM内存模型之线程独占部分"></a>JVM内存模型之线程独占部分</h3><ol>
<li><p>程序计数器(Program Counter Register)</p>
<blockquote>
<p>a. 作用：当前线程所执行的字节码的行号指示器(程序计数器是逻辑计数器)<br>b. JVM中的字节码解释器工作时：就是改变计数器的值来选取下一条需要执行的字节码指令，如分支、循环、跳转、异常处理、线程恢复等都依赖程序计数器实现<br>c. 程序计数器与线程是一对一的关系，即程序计数器的内存空间是线程私有的。 JVM的多线程是通过线程轮流切换、并分配处理器执行实现的。所以在任意一个确定的时间，一个处理器只会执行一个线程中的指令，因此为了线程切换后能恢复到正确的执行位置，每个线程都要有一个独立的程序计数器，各线程之间的程序计数器互补影响，独立存储。<br>d. 如果线程正在执行的是Java方法，则程序计数器的值为正在执行的字节码的指令行号; 如果是native方法，则程序计数器的值为Undefined————即只为Java方法计数<br>e. 唯一不会发生内存泄露即OOM的内存空间 ，因为只是记录字节码的行号</p>
</blockquote>
</li>
<li><p>虚拟机栈(Stack)</p>
<blockquote>
<p>a. 虚拟机栈是<strong>Java方法执行的内存模型</strong>，也是线程私有的。<br>b. 虚拟机栈用于存储单个线程每个方法执行的栈帧, 所以包含多个栈帧，并且有固定的容量。因为每个Java方法被执行时JVM都会自动分配一块内存空间来创建一个栈帧，并将栈帧压入虚拟机栈中；<br>c. 栈帧：是Java方法运行期间的基础数据结构。栈帧用于存储局部变量表、操作数栈、动态连接、返回地址等每个方法执行过程中对应虚拟机栈从入栈到出栈的全过程。如下图所示<br>d. 栈帧持有局部变量和部分结果，及参与方法的调用和返回。<br>e. 当方法调用结束时，栈帧从虚拟机栈中出栈，并被销毁，所以虚拟机栈的内存不需要GC回收。<br>f. 虚拟机栈是JVM自动管理的。可通过jstack来分析线程的虚拟机栈信息</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191217152432416.jpg" alt="栈帧"></p>
<p>局部变量表与操作数栈的关系：</p>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="bullet">1. </span>局部变量表: 包含方法执行过程中的所有变量</span><br><span class="line"><span class="bullet">2. </span>操作数栈：在执行字节码指令过程中会用到。 大部分JVM操作字节码都花费在操作数栈的操作上，包括：入栈、出栈、交换、复制、产生消费变量</span><br><span class="line"><span class="bullet">3. </span>两者关系：局部变量表为操作数栈提供必要的数据支撑。局部变量表与操作数栈通过字节码指令频繁执行出栈和入栈等操作；</span><br></pre></td></tr></table></figure>

<p>通过如下的代码分析局部变量表与操作数栈的关系：</p>
<figure class="highlight livescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">CodeDemo</span> &#123;</span></span><br><span class="line"></span><br><span class="line">    public static int add(int a, int b)&#123;</span><br><span class="line">        int c = <span class="number">0</span>;</span><br><span class="line">        c = a + b;</span><br><span class="line">        <span class="keyword">return</span> c;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">///</span></span><br><span class="line"><span class="regexp">javac CodeDemo.java  //</span>编译</span><br><span class="line">javap -verbose CodeDemo.class  <span class="regexp">//反编译, 得到的代码如下：</span></span><br><span class="line"><span class="regexp">//</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span><span class="regexp">////</span></span><br><span class="line"></span><br><span class="line">Classfile /xxx/CodeDemo.class  <span class="comment"># 文件信息</span></span><br><span class="line">  Last modified <span class="number">2019</span>-<span class="number">12</span>-<span class="number">17</span>; size <span class="number">290</span> bytes</span><br><span class="line">  MD5 checksum d3b5ddc9ef6ae4070da8bb8658c78986</span><br><span class="line">  Compiled <span class="keyword">from</span> <span class="string">"CodeDemo.java"</span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">CodeDemo</span></span></span><br><span class="line">  minor version: <span class="number">0</span></span><br><span class="line">  major version: <span class="number">52</span></span><br><span class="line">  flags: ACC_PUBLIC, ACC_SUPER  <span class="comment"># 描述类信息：公用的，集成自Object</span></span><br><span class="line">Constant pool:                  <span class="comment"># 常量池信息</span></span><br><span class="line">   <span class="comment">#1 = Methodref          #3.#12         // java/lang/Object."&lt;init&gt;":()V</span></span><br><span class="line">   <span class="comment">#2 = Class              #13            // com/aiolos/interview/java06/jvm/CodeDemo</span></span><br><span class="line">   <span class="comment">#3 = Class              #14            // java/lang/Object</span></span><br><span class="line">   <span class="comment">#4 = Utf8               &lt;init&gt;</span></span><br><span class="line">   <span class="comment">#5 = Utf8               ()V</span></span><br><span class="line">   <span class="comment">#6 = Utf8               Code</span></span><br><span class="line">   <span class="comment">#7 = Utf8               LineNumberTable</span></span><br><span class="line">   <span class="comment">#8 = Utf8               add</span></span><br><span class="line">   <span class="comment">#9 = Utf8               (II)I</span></span><br><span class="line">  <span class="comment">#10 = Utf8               SourceFile</span></span><br><span class="line">  <span class="comment">#11 = Utf8               CodeDemo.java</span></span><br><span class="line">  <span class="comment">#12 = NameAndType        #4:#5          // "&lt;init&gt;":()V</span></span><br><span class="line">  <span class="comment">#13 = Utf8               com/aiolos/interview/java06/jvm/CodeDemo</span></span><br><span class="line">  <span class="comment">#14 = Utf8               java/lang/Object</span></span><br><span class="line">&#123;</span><br><span class="line">  public com.aiolos.interview.java06.jvm.CodeDemo();  <span class="comment"># 构造函数的初始化过程，同本文之前的描述</span></span><br><span class="line">    descriptor: ()V</span><br><span class="line">    flags: ACC_PUBLIC</span><br><span class="line">    Code:</span><br><span class="line">      stack=<span class="number">1</span>, locals=<span class="number">1</span>, args_size=<span class="number">1</span></span><br><span class="line">         <span class="number">0</span>: aload_0</span><br><span class="line">         <span class="number">1</span>: invokespecial <span class="comment">#1                  // Method java/lang/Object."&lt;init&gt;":()V</span></span><br><span class="line">         <span class="number">4</span>: <span class="keyword">return</span></span><br><span class="line">      LineNumberTable:</span><br><span class="line">        line <span class="number">3</span>: <span class="number">0</span></span><br><span class="line"></span><br><span class="line">  public static int add(int, int);   <span class="comment"># 重点研究的方法</span></span><br><span class="line">    descriptor: (II)I                <span class="comment"># 描述方法：(II)表示接受2个int参数，I表示返回的也是int</span></span><br><span class="line">    flags: ACC_PUBLIC, ACC_STATIC    <span class="comment"># 方法的访问属性，public、static</span></span><br><span class="line">    Code:</span><br><span class="line">      stack=<span class="number">2</span>, locals=<span class="number">3</span>, args_size=<span class="number">2</span> <span class="comment"># stack=2表示操作数栈的深度为2；locals=3表示本地变量容量为3；args_size=2表示参数为2个</span></span><br><span class="line">         <span class="number">0</span>: iconst_0                 <span class="comment"># iconst_0表示将int型值0压入操作数栈中</span></span><br><span class="line">         <span class="number">1</span>: istore_2                 <span class="comment"># istore_2表示将操作数栈顶的值0弹出，存储到局部变量表下标为2的位置上(istore表示出栈)</span></span><br><span class="line">         <span class="number">2</span>: iload_0                  <span class="comment"># iload_0表示将局部变量表中第1个值压入到操作数栈中(iload表示入栈)</span></span><br><span class="line">         <span class="number">3</span>: iload_1                  <span class="comment"># iload_1表示将局部变量表中第2个值压入到操作数栈中</span></span><br><span class="line">         <span class="number">4</span>: iadd                     <span class="comment"># 弹出操作数栈的数1和2，执行iadd相加，将结果3压入操作数栈中</span></span><br><span class="line">         <span class="number">5</span>: istore_2                 <span class="comment"># istore_2表示将操作数栈顶的值3弹出，存储到局部变量表下标为2的位置上，替换掉0</span></span><br><span class="line">         <span class="number">6</span>: iload_2                  <span class="comment"># iload_2表示将局部变量表中第3个值压入到操作数栈中</span></span><br><span class="line">         <span class="number">7</span>: ireturn                  <span class="comment"># 通过ireturn将操作数栈中的值3返回，完成方法的执行，并销毁栈帧</span></span><br><span class="line">      LineNumberTable:     <span class="comment"># 行号对应关系表</span></span><br><span class="line">        line <span class="number">6</span>: <span class="number">0</span>          <span class="comment"># 代码第6行对应字节码第0行，即 0: iconst_0</span></span><br><span class="line">        line <span class="number">7</span>: <span class="number">2</span>          <span class="comment"># 代码第7行对应字节码第2行，即 2: iload_0</span></span><br><span class="line">        line <span class="number">8</span>: <span class="number">6</span></span><br><span class="line">&#125;</span><br><span class="line">SourceFile: <span class="string">"CodeDemo.java"</span></span><br></pre></td></tr></table></figure>

<p>局部变量表与操作数栈的关系：<br><img src="/blog/images/20191217172604475.jpg" alt="局部变量表与操作数栈的关系"></p>
<p>递归为什么会引发java.lang.StackOverflowError异常</p>
<blockquote>
<p>由于递归方法每次调用自身都会创建一个栈帧，所以如果递归层次过深，栈帧数超出虚拟机栈的深度(每个线程中虚拟机栈深度固定)，就会引发java.lang.StackOverflowError异常。解决办法是限制递归的深度。</p>
</blockquote>
<p>虚拟机栈过多会引发java.lang.OutOfMemoryError异常，这是因为：当虚拟机栈动态扩展时无法申请到足够多的内存时，就会引发该异常。</p>
<ol start="3">
<li>本地方法栈<blockquote>
<p>与虚拟机栈相似，主要作用于标注了native的方法。<br>Java方法使用虚拟机栈；native方法使用本地方法栈</p>
</blockquote>
</li>
</ol>
<h3 id="JVM内存模型之线程共享部分"><a href="#JVM内存模型之线程共享部分" class="headerlink" title="JVM内存模型之线程共享部分"></a>JVM内存模型之线程共享部分</h3><ol>
<li>MetaSpace(元空间)<blockquote>
<p>从JDK8开始，将类的元数据放入本地堆内存中，这块区域就叫MetaSpace。这块区域在JDK7及之前，是属于永久代(PermGen)。从JDK8开始，使用MetaSpace(元空间)替代了永久代(PermGen)</p>
</blockquote>
</li>
</ol>
<p>MetaSpace(元空间)与永久代(PermGen)的区别：</p>
<blockquote>
<p>相同点：都是用来存储类的相关信息，包括类的方法、属性等。<br>不同点：<strong>元空间使用本机内存，而永久代使用的是JVM的内存</strong>。使用本地内存的好处是java.lang.OutOfMemoryError:PermGen space异常不会再存在了，因为类的元数据的分配只受本地内存大小的限制了，理论上本地内存剩余多少，MetaSpace就可以有多大。<br>MetaSpace没有了字符串常量池，它在JDK7已经移到了堆中。</p>
</blockquote>
<p>永久代(PermGen)相比MetaSpace(元空间)的劣势(使用元空间可以很好的解决如下四个问题)：</p>
<blockquote>
<p>a. 字符串产量池存在永久代中，容易出现性能问题和内存溢出。<br>b. 类和方法的信息大小难以确认，给永久代的大小指定带来困难。<br>c. 永久代会为GC带来不必要的复杂性，性能较低<br>d. 方便HotSpot与其他JVM如Jrockit的集成</p>
</blockquote>
<ol start="2">
<li>Java堆(Heap)<blockquote>
<p>Heap是JVM管理内存中的最大一块区域，在JVM启动时创建，所有线程共享。<br>Heap是对象实例的分配区域，它的唯一作用是存放对象实例。<br>Heap可以是物理上不连续的内存空间，只要逻辑上是连续的即可。<br>Heap的大小是可扩展的，即通过-Xms、-Xmx来控制<br>Heap是GC管理的主要区域<br>如果Heap中没有内存完成实例分配，并且Heap也无法扩展时，就会引发java.lang.OutOfMemoryError异常。</p>
</blockquote>
</li>
</ol>
<p>内存中各区域大小如下图：<br><img src="/blog/images/20191218064330907.jpg" alt="内存中各区域大小"></p>
<h2 id="JVM内存模型之常考题解析"><a href="#JVM内存模型之常考题解析" class="headerlink" title="JVM内存模型之常考题解析"></a>JVM内存模型之常考题解析</h2><ol>
<li>JVM三大性能调优参数-Xms、-Xmx、-Xss的含义<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在使用java命令执行jar程序时，可以通过java -Xms128m -Xmx128m -Xss256k -jar xxxx.jar命令来指定JVM的堆和线程所占内存的大小</span></span><br><span class="line">-<span class="string">Xss:</span>  规定了每个线程的虚拟机栈(即堆栈)的大小。一般情况下<span class="number">256</span>k是足够的。这个参数会影响进程中并发线程数的大小</span><br><span class="line">-<span class="string">Xms:</span>  规定了Java堆的初始值。即进程刚创建出来时，专属Java堆的大小。当对象容量超出Java堆的初始值，Java堆将自动扩容</span><br><span class="line">-<span class="string">Xmx:</span>  规定了Java堆的最大值。</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><strong>注意：很多情况下，将-Xmx和-Xms的值设置为同样大小，因为当Java堆不够用而进行扩容时会发生内存抖动，影响<br>程序运行时的稳定性。</strong></p>
<ol start="2">
<li>Java内存模型中堆和栈的区别<blockquote>
<p>程序运行时的内存分配策略有三种：静态存储、栈式存储、堆式存储</p>
</blockquote>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">静态存储：是指在编译时就能确定每个数据目标在运行时的存储空间需求，因而在编译时就可以为它们分配固定的内存空间大小。———— 这种分配策略要求程序代码中不允许有可变的数据结构，也不允许有嵌套、递归的结构出现，因为它们都将导致编译器无法计算准确的存储空间。</span><br><span class="line">栈式存储：是指程序对数据区存储需求在编译时未知，运行时进入模块入口前才确定。是动态的存储分配，是由一个类似堆栈的运行栈来实现。 按照先进后出的原则分配内存。————这种分配策略规定：在运行时，进入一个程序模块前必须知道该程序模块所需的数据区的大小，才能发配内存空间。</span><br><span class="line">堆式存储：专门负责在编译时或运行时进入模块入口处都无法确认存储要求的数据结构的内存分配，如可变长度字符串和对象实例。堆由大片可利用块或空闲块组成。堆中的内存可按照任意顺序分配和释放。是动态分配</span><br></pre></td></tr></table></figure>

<p>堆和栈的联系： 创建的对象和数组都保存在堆中，想引用对象、数组时，可以在栈里定义变量保存堆中目标的首地址——这就是引用变量。如下图所示：</p>
<blockquote>
<p>引用变量在其作用域之外就被销毁，但其引用的对象和数组只有在没有引用变量指向它们之后的某个时刻才有GC销毁。</p>
</blockquote>
<p><img src="/blog/images/20191218120630804.jpg" alt="堆和栈的联系"></p>
<p>Java内存模型中堆和栈的区别：</p>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="bullet">1. </span>管理方式不同： JVM可以对栈进行内存管理，栈能自动释放其内存；JVM对堆内存不会进行释放操作，需要GC来回收这部分内存</span><br><span class="line"><span class="bullet">2. </span>空间大小不同：栈比堆小。因为在Java程序中，堆空间需要存储较多的Java对象数据</span><br><span class="line"><span class="bullet">3. </span>碎片相关：栈产生的碎片远小于堆。 堆空间相对栈空间，活动量更大，存在更长期的堆空间分配和释放操作，而且GC不是实时回收，这都导致堆空间中的碎片累计起来。 栈空间本身是一个栈的数据结构，在使用过程中很少出现碎片。</span><br><span class="line"><span class="bullet">4. </span>分配方式不同：栈支持静态分配和动态分配；堆只支持动态分配</span><br><span class="line"><span class="bullet">5. </span>内存释放问题：栈空间分配的内存无需我们考虑释放问题(由JVM自动释放)；堆空间分配的内存，即使有GC回收内存，也要我们考虑释放的问题</span><br><span class="line"><span class="bullet">6. </span>效率不同：栈的效率比堆高。因为内存本身就是一个栈结构，而堆在计算机底层是通过双向链表来实现的</span><br></pre></td></tr></table></figure>

<p>栈空间相比堆空间的弱点：</p>
<blockquote>
<p>灵活程度不够，特别是动态分配内存时。 这也是堆空间最大的优点，因为它在计算机底层是通过双向链表来实现的。</p>
</blockquote>
<ol start="3">
<li><p>元空间、堆、线程独占部分之间的联系——内存角度<br><img src="/blog/images/20191218140610157.jpg" alt="元空间、堆、线程独占部分之间的联系"></p>
</li>
<li><p>JDK6与JDK6+版本之间的intern()方法的区别</p>
<blockquote>
<p>答案：在JDK6中，intern()方法仅能向方法字符串常量池中添加字符串常量对象；而JDK6+，intern()不仅能向方法字符串常量池中添加字符串常量对象，还能添加字符串常量在堆中的引用</p>
</blockquote>
</li>
</ol>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//intern()方法的用法</span></span><br><span class="line"><span class="keyword">String</span> s = <span class="keyword">new</span> <span class="keyword">String</span>(<span class="string">"a"</span>);</span><br><span class="line">s.intern();</span><br><span class="line"></span><br><span class="line">JDK6：当调用intern()方法时，如果字符串常量池先前已创建出该字符串对象，则返回池中</span><br><span class="line">的该字符串的引用。否则，将此字符串对象添加到字符串常量池中，并且返回该字符串对象的引用。</span><br><span class="line"></span><br><span class="line">JDK6+：当调用intern()方法时，如果字符串常量池先前已创建出该字符串对象，则返回池中</span><br><span class="line">的该字符串的引用。否则，如果该字符串对象已存在于Java堆中，则将堆中该对象的引用添加到字符串常量池中，并且返回该引用。如果堆中不存在，则在池中创建该字符串并返回其引用。</span><br></pre></td></tr></table></figure>

<p>不同JDK版本下intern()方法的区别如下图(<strong>???第一次返回false处有疑问</strong>)：</p>
<blockquote>
<p>JDK6中，通过intern()方法只能将堆中字符串对象的副本添加到字符串常量池中。它们的地址不同<br>JDK7+中，通过intern()方法不仅能将堆中字符串对象的副本添加到字符串常量池中，还能将字符串对象的引用添加到字符串常量池中;</p>
</blockquote>
<p><img src="/blog/images/20191218150352284.jpg" alt="不同JDK版本下intern()方法的区别"></p>
<p>在JDK7以后，方法区中的字符串常量池被移动到堆中，这是因为在JDK7之前，字符串常量池存在于永久代中，而永久代的内存极为有限，如果频繁调用intern()方法在字符串常量池中创建字符串对象，会挤爆字符串常量池，进而引发java.lang.OutOfMemoryError:PermGen space的异常。<br><img src="/blog/images/20191217142013010.jpg" alt="从线程的角度看JVM内存模型"></p>
<p>测试在不同JDK下是否能触发java.lang.OutOfMemoryError:PermGen space的异常，运行结果如下图：<br><img src="/blog/images/20191218144127567.jpg" alt="在JDK6在模拟引发java.lang.OutOfMemoryError:PermGen space的异常"></p>
<p>说明在JDK7+，字符串常量池已经不受永久代的约束了！</p>
<h2 id="关于ClassLoader的参考博客"><a href="#关于ClassLoader的参考博客" class="headerlink" title="关于ClassLoader的参考博客"></a>关于ClassLoader的参考博客</h2><p>《面试官：说说双亲委派模型？》 <a href="https://baijiahao.baidu.com/s?id=1633056679004596814&amp;wfr=spider&amp;for=pc" target="_blank" rel="noopener">https://baijiahao.baidu.com/s?id=1633056679004596814&amp;wfr=spider&amp;for=pc</a><br>《JVM–双亲委派机制》<a href="https://www.cnblogs.com/parent-absent-son/p/9872443.html" target="_blank" rel="noopener">https://www.cnblogs.com/parent-absent-son/p/9872443.html</a></p>
<p>通过上述两篇博客，摘录如下结论：</p>
<ol>
<li><p>类的加载阶段：分为加载、连接、初始化三个阶段</p>
</li>
<li><p>类加载器：在加载阶段(此加载阶段是指加载、连接、初始化中的加载)是通过类的全限定名来获取定义了此类的class文件的二进制字节流。Java特意把加载阶段这一步抽出来放到java虚拟机外部用类加载器来实现，以便让应用程序可以按需自定义类加载器，来决定如何去获取所需要的类。</p>
</li>
<li><p>通俗的讲，虚拟机是根据类的全限定名来加载类的，那么有个问题，如果同时存在两个或多个全限定名完全一致的情况下。该如何选择加载哪个类。这就是双亲委派机制要做的工作。</p>
<blockquote>
<p>在这里强加个知识点：比较两个类是否“相等”，只有在这两个类是由同一个类加载器加载的前提下才有真正的意义，否则，即使这两个类来源于同一个class文件，被同一个虚拟机加载，只要加载他们的类加载器不同，那这两个类就必定不相等。————即在Java中任意一个类都是由这个类本身和加载这个类的类加载器来确定这个类在JVM中的唯一性。所以即使都来自于同一个class文件但是由不同类加载器加载的那就是两个独立的类。</p>
</blockquote>
</li>
<li><p>类加载器除了能用来加载类，还能用来作为类的层次划分。</p>
</li>
<li><p>Java自身提供4种类加载器</p>
<blockquote>
<p>a、启动类加载器(Bootstrap ClassLoader),它是属于虚拟机自身的一部分，用C++实现的，主要负责加载%JAVA_HOME%\lib目录下所有的jar包或是-Xbootclasspath指定的路径中的类库并且文件名是被虚拟机识别的文件。它等于是所有类加载器的爸爸。<br>b、扩展类加载器(Extension ClassLoader),它是Java实现的，独立于虚拟机，主要负责加载%JAVA_HOME%\lib\ext目录下所有的jar包或被java.ext.dirs系统变量所指定的路径的类库。<br>c、应用程序类加载器(Application ClassLoader),它是Java实现的，独立于虚拟机。主要负责加载用户类路径(classPath)上的类库，如果没有实现自定义的类加载器,那这个类加载器就是程序中的默认加载器。<br>d、用户自定义类加载器</p>
</blockquote>
</li>
<li><p>各加载器之间的层次关系<br><img src="/blog/images/20191217092006619.jpg" alt="加载器之间的层次关系"></p>
</li>
<li><p>双亲委派机制的工作过程(双亲委派机制的原理)：</p>
<blockquote>
<p>1-类加载器收到类加载的请求；<br>2-把这个请求委托给父加载器去完成，一直向上委托，直到启动类加载器；<br>3-启动类加载器检查能不能加载（使用findClass()方法），能就加载（结束）；否则，抛出异常并向下通知子加载器进行加载。<br>4-重复步骤三；</p>
</blockquote>
</li>
<li><p>双亲委派模型不是一种强制性约束，也就是你不这么做也不会报错怎样的，它是一种JAVA设计者推荐使用类加载器的方式。</p>
</li>
<li><p>双亲委派有啥好处呢？它使得类有了层次的划分。</p>
<blockquote>
<p>就拿java.lang.Object来说，你加载它经过一层层委托最终是由Bootstrap ClassLoader来加载的，也就是最终都是由Bootstrap ClassLoader去找<java_home>\lib中rt.jar里面的java.lang.Object加载到JVM中。</java_home></p>
</blockquote>
</li>
</ol>
<blockquote>
<p>这样如果有不法分子自己造了个java.lang.Object,里面嵌了不好的代码，如果我们是按照双亲委派模型来实现的话，最终加载到JVM中的只会是我们rt.jar里面的东西，也就是这些核心的基础类代码得到了保护。因为这个机制使得系统中只会出现一个java.lang.Object。不会乱套了。你想想如果我们JVM里面有两个Object,那岂不是天下大乱了。</p>
</blockquote>
<ol start="10">
<li>有些情况不得不违反双亲委派模型这个约束，例如JDBC<blockquote>
<p>你先得知道SPI(Service Provider Interface)，这玩意和API不一样，它是面向拓展的，也就是我定义了这个SPI，具体如何实现由扩展者实现。我就是定了个规矩。</p>
</blockquote>
</li>
</ol>
<p>JDBC就是如此，在rt里面定义了这个SPI，那mysql有mysql的jdbc实现，oracle有oracle的jdbc实现，反正我java不管你内部如何实现的，反正你们都得统一按我这个来，这样我们java开发者才能容易的调用数据库操作。</p>
<p>所以因为这样那就不得不违反这个约束啊，Bootstrap ClassLoader就得委托子类来加载数据库厂商们提供的具体实现。因为它的手只能摸到<java_home>\lib中，其他的它无能为力。这就违反了自下而上的委托机制了。</java_home></p>
<p>Java就搞了个线程上下文类加载器，通过setContextClassLoader()默认情况就是应用程序类加载器然后Thread.current.currentThread().getContextClassLoader()获得类加载器来加载。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Java面试/" rel="tag"># Java面试</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/06/spring-cloud-weather-8/" rel="next" title="【八】从天气项目看Spring Cloud微服务治理——微服务的熔断机制">
                <i class="fa fa-chevron-left"></i> 【八】从天气项目看Spring Cloud微服务治理——微服务的熔断机制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/12/10/spring-cloud-weather-9/" rel="prev" title="【九】从天气项目看Spring Cloud微服务治理——微服务的自动扩展介绍">
                【九】从天气项目看Spring Cloud微服务治理——微服务的自动扩展介绍 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#课程简介"><span class="nav-number">1.</span> <span class="nav-text">课程简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#谈谈你对Java的理解"><span class="nav-number">2.</span> <span class="nav-text">谈谈你对Java的理解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#平台无关性如何实现"><span class="nav-number">3.</span> <span class="nav-text">平台无关性如何实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#编译时：将java源文件编译为class文件"><span class="nav-number">3.1.</span> <span class="nav-text">编译时：将java源文件编译为class文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行时：JVM运行class文件"><span class="nav-number">3.2.</span> <span class="nav-text">运行时：JVM运行class文件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JVM如何加载和运行class文件"><span class="nav-number">4.</span> <span class="nav-text">JVM如何加载和运行class文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是反射"><span class="nav-number">5.</span> <span class="nav-text">什么是反射</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#谈谈ClassLoader"><span class="nav-number">6.</span> <span class="nav-text">谈谈ClassLoader</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ClassLoader的双亲委派机制"><span class="nav-number">7.</span> <span class="nav-text">ClassLoader的双亲委派机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#loadClass和forName的区别"><span class="nav-number">8.</span> <span class="nav-text">loadClass和forName的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JVM内存模型"><span class="nav-number">9.</span> <span class="nav-text">JVM内存模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#从线程的角度看JVM内存模型"><span class="nav-number">10.</span> <span class="nav-text">从线程的角度看JVM内存模型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#JVM内存模型之线程独占部分"><span class="nav-number">10.1.</span> <span class="nav-text">JVM内存模型之线程独占部分</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JVM内存模型之线程共享部分"><span class="nav-number">10.2.</span> <span class="nav-text">JVM内存模型之线程共享部分</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JVM内存模型之常考题解析"><span class="nav-number">11.</span> <span class="nav-text">JVM内存模型之常考题解析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关于ClassLoader的参考博客"><span class="nav-number">12.</span> <span class="nav-text">关于ClassLoader的参考博客</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
